/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.msu.server.schedule;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import io.iec.edp.caf.msu.server.storage.MsuStorage;
import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import io.iec.edp.caf.tenancy.core.context.MultiTenantContextHolder;
import lombok.var;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;

/**
 * @author Leon Huo
 */

@EnableScheduling
public class HealthCheckSchedule {
    private MsuStorage storage;
    private NamingService namingService;

    public HealthCheckSchedule(MsuStorage storage, NamingService namingService) {
        this.storage = storage;
        this.namingService = namingService;
    }

    @Scheduled(fixedDelay = 20 * 1000)
    public void checkServiceState() throws NacosException {
        var nacosServiceList = namingService.getServicesOfServer(1, 1000).getData();
        var storageServiceList = storage.getEnabledServiceUnitInfo();
        var deleteServiceList = new ArrayList<String>();
        for (var service : storageServiceList) {
            if (!nacosServiceList.contains(service.getServiceUnitName()))
                deleteServiceList.add(service.getServiceUnitName());
        }

        if (!deleteServiceList.isEmpty()) {
            try{

                //msu检查默认走主库
                MultiTenantContextInfo contextInfo = new MultiTenantContextInfo();
                contextInfo.setMasterDb(true);
                MultiTenantContextHolder.set(contextInfo);
                storage.deleteBySu(deleteServiceList);
            }finally {
                MultiTenantContextHolder.set(null);
            }

        }
    }
}
